﻿using LY.Manage.Model;
using LY.Manage.Model.EnumType;
using LY.Manage.Model.SearchParam;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace LY.Manage.WebApp.Controllers
{
    public class UserInfoController : Controller //BaseController
    {
        //
        // GET: /UserInfo/

        IBLL.IUserInfoService UserInfoService { get; set; }
        IBLL.IRoleInfoService RoleInfoService { get; set; }

        IBLL.IActionInfoService ActionInfoService { get; set; }

        IBLL.IR_UserInfo_ActionInfoService R_UserInfo_ActionInfoService { get; set; }
        IBLL.IDepartmentService DepartmentService { get; set; }


        public ActionResult Index()
        {
          

            return View();
        }
        public ActionResult Index1()
        {


            return View();
        }


//        {
//  code: 0,
//  msg: "",
//  count: 1000,
//  data: []
//} 


        public class User1
        {            

            public int id { get; set; }
            public string username { get; set; }
        }

        public class LayUIResult
        {
            public int code { get; set; }
            public string msg { get; set; }
            public int count { get; set; }
            public List<User1> data { get; set; }
        }

        #region 获取用户列表数据

        public ActionResult GetUserInfoList()
        {
            ////如果异常记录日志抛出去
            //int pageIndex = Request["page"] != null ? int.Parse(Request["page"]) : 1;
            //int pageSize = Request["rows"] != null ? int.Parse(Request["rows"]) : 20;

            //int totalCount = 0;
            //string name = Request["name"];
            //string remark = Request["remark"];
            ////构建搜索参数
          
            //UserInfoParam userInfoParam = new UserInfoParam();
            //userInfoParam.PageIndex = pageIndex;
            //userInfoParam.PageSize = pageSize;
            //userInfoParam.UserName = name;
            //userInfoParam.Remark = remark;
            ////根据搜索参数搜索数据

            //var userInfoList = UserInfoService.LoadSearchEntities(userInfoParam);

            //var depList=DepartmentService.LoadEntities(u=>true);

            //var temp = from u in userInfoList 
            //            join t in depList
            //            on u.DepId  equals t.ID
            //            select new
            //            {
                           
            //                ID = u.ID,
            //                UName = u.UName,
            //                UPwd = u.UPwd,
            //                Remark = u.Remark,
            //                SubTime = u.SubTime,
            //                Sort=u.Sort,
            //                t.DepName

            //            };


            ////rows 与 total是固定的 不能随便定义,因为EasyUI用的是这两个数据
            //return Json(new { 
            //    rows=temp,total=userInfoParam.TotalCount
            //});

            LayUIResult layResult = new LayUIResult();
            layResult.code = 200;
            layResult.count = 10;
            layResult.data = new List<User1>() { 
                new User1(){ id=1,username="liyang"},
                new User1(){ id=2,username="liyang"},
                new User1(){ id=3,username="liyang"}
            
            };

            return Json(layResult);
            //return Content(  Newtonsoft.Json.JsonConvert.SerializeObject( layResult));
            //string jos = "{\"code\":0,\"msg\":\"\",\"count\":1000,\"data\":[{\"id\":10000,\"username\":\"user-0\",\"sex\":\"女\",\"city\":\"城市-0\",\"sign\":\"签名-0\",\"experience\":255,\"logins\":24,\"wealth\":82830700,\"classify\":\"作家\",\"score\":57},{\"id\":10001,\"username\":\"user-1\",\"sex\":\"男\",\"city\":\"城市-1\",\"sign\":\"签名-1\",\"experience\":884,\"logins\":58,\"wealth\":64928690,\"classify\":\"词人\",\"score\":27},{\"id\":10002,\"username\":\"user-2\",\"sex\":\"女\",\"city\":\"城市-2\",\"sign\":\"签名-2\",\"experience\":650,\"logins\":77,\"wealth\":6298078,\"classify\":\"酱油\",\"score\":31},{\"id\":10003,\"username\":\"user-3\",\"sex\":\"女\",\"city\":\"城市-3\",\"sign\":\"签名-3\",\"experience\":362,\"logins\":157,\"wealth\":37117017,\"classify\":\"诗人\",\"score\":68},{\"id\":10004,\"username\":\"user-4\",\"sex\":\"男\",\"city\":\"城市-4\",\"sign\":\"签名-4\",\"experience\":807,\"logins\":51,\"wealth\":76263262,\"classify\":\"作家\",\"score\":6},{\"id\":10005,\"username\":\"user-5\",\"sex\":\"女\",\"city\":\"城市-5\",\"sign\":\"签名-5\",\"experience\":173,\"logins\":68,\"wealth\":60344147,\"classify\":\"作家\",\"score\":87},{\"id\":10006,\"username\":\"user-6\",\"sex\":\"女\",\"city\":\"城市-6\",\"sign\":\"签名-6\",\"experience\":982,\"logins\":37,\"wealth\":57768166,\"classify\":\"作家\",\"score\":34},{\"id\":10007,\"username\":\"user-7\",\"sex\":\"男\",\"city\":\"城市-7\",\"sign\":\"签名-7\",\"experience\":727,\"logins\":150,\"wealth\":82030578,\"classify\":\"作家\",\"score\":28},{\"id\":10008,\"username\":\"user-8\",\"sex\":\"男\",\"city\":\"城市-8\",\"sign\":\"签名-8\",\"experience\":951,\"logins\":133,\"wealth\":16503371,\"classify\":\"词人\",\"score\":14},{\"id\":10009,\"username\":\"user-9\",\"sex\":\"女\",\"city\":\"城市-9\",\"sign\":\"签名-9\",\"experience\":484,\"logins\":25,\"wealth\":86801934,\"classify\":\"词人\",\"score\":75},{\"id\":10010,\"username\":\"user-10\",\"sex\":\"女\",\"city\":\"城市-10\",\"sign\":\"签名-10\",\"experience\":1016,\"logins\":182,\"wealth\":71294671,\"classify\":\"诗人\",\"score\":34},{\"id\":10011,\"username\":\"user-11\",\"sex\":\"女\",\"city\":\"城市-11\",\"sign\":\"签名-11\",\"experience\":492,\"logins\":107,\"wealth\":8062783,\"classify\":\"诗人\",\"score\":6},{\"id\":10012,\"username\":\"user-12\",\"sex\":\"女\",\"city\":\"城市-12\",\"sign\":\"签名-12\",\"experience\":106,\"logins\":176,\"wealth\":42622704,\"classify\":\"词人\",\"score\":54},{\"id\":10013,\"username\":\"user-13\",\"sex\":\"男\",\"city\":\"城市-13\",\"sign\":\"签名-13\",\"experience\":1047,\"logins\":94,\"wealth\":59508583,\"classify\":\"诗人\",\"score\":63},{\"id\":10014,\"username\":\"user-14\",\"sex\":\"男\",\"city\":\"城市-14\",\"sign\":\"签名-14\",\"experience\":873,\"logins\":116,\"wealth\":72549912,\"classify\":\"词人\",\"score\":8},{\"id\":10015,\"username\":\"user-15\",\"sex\":\"女\",\"city\":\"城市-15\",\"sign\":\"签名-15\",\"experience\":1068,\"logins\":27,\"wealth\":52737025,\"classify\":\"作家\",\"score\":28},{\"id\":10016,\"username\":\"user-16\",\"sex\":\"女\",\"city\":\"城市-16\",\"sign\":\"签名-16\",\"experience\":862,\"logins\":168,\"wealth\":37069775,\"classify\":\"酱油\",\"score\":86},{\"id\":10017,\"username\":\"user-17\",\"sex\":\"女\",\"city\":\"城市-17\",\"sign\":\"签名-17\",\"experience\":1060,\"logins\":187,\"wealth\":66099525,\"classify\":\"作家\",\"score\":69},{\"id\":10018,\"username\":\"user-18\",\"sex\":\"女\",\"city\":\"城市-18\",\"sign\":\"签名-18\",\"experience\":866,\"logins\":88,\"wealth\":81722326,\"classify\":\"词人\",\"score\":74},{\"id\":10019,\"username\":\"user-19\",\"sex\":\"女\",\"city\":\"城市-19\",\"sign\":\"签名-19\",\"experience\":682,\"logins\":106,\"wealth\":68647362,\"classify\":\"词人\",\"score\":51},{\"id\":10020,\"username\":\"user-20\",\"sex\":\"男\",\"city\":\"城市-20\",\"sign\":\"签名-20\",\"experience\":770,\"logins\":24,\"wealth\":92420248,\"classify\":\"诗人\",\"score\":87},{\"id\":10021,\"username\":\"user-21\",\"sex\":\"男\",\"city\":\"城市-21\",\"sign\":\"签名-21\",\"experience\":184,\"logins\":131,\"wealth\":71566045,\"classify\":\"词人\",\"score\":99},{\"id\":10022,\"username\":\"user-22\",\"sex\":\"男\",\"city\":\"城市-22\",\"sign\":\"签名-22\",\"experience\":739,\"logins\":152,\"wealth\":60907929,\"classify\":\"作家\",\"score\":18},{\"id\":10023,\"username\":\"user-23\",\"sex\":\"女\",\"city\":\"城市-23\",\"sign\":\"签名-23\",\"experience\":127,\"logins\":82,\"wealth\":14765943,\"classify\":\"作家\",\"score\":30},{\"id\":10024,\"username\":\"user-24\",\"sex\":\"女\",\"city\":\"城市-24\",\"sign\":\"签名-24\",\"experience\":212,\"logins\":133,\"wealth\":59011052,\"classify\":\"词人\",\"score\":76},{\"id\":10025,\"username\":\"user-25\",\"sex\":\"女\",\"city\":\"城市-25\",\"sign\":\"签名-25\",\"experience\":938,\"logins\":182,\"wealth\":91183097,\"classify\":\"作家\",\"score\":69},{\"id\":10026,\"username\":\"user-26\",\"sex\":\"男\",\"city\":\"城市-26\",\"sign\":\"签名-26\",\"experience\":978,\"logins\":7,\"wealth\":48008413,\"classify\":\"作家\",\"score\":65},{\"id\":10027,\"username\":\"user-27\",\"sex\":\"女\",\"city\":\"城市-27\",\"sign\":\"签名-27\",\"experience\":371,\"logins\":44,\"wealth\":64419691,\"classify\":\"诗人\",\"score\":60},{\"id\":10028,\"username\":\"user-28\",\"sex\":\"女\",\"city\":\"城市-28\",\"sign\":\"签名-28\",\"experience\":977,\"logins\":21,\"wealth\":75935022,\"classify\":\"作家\",\"score\":37},{\"id\":10029,\"username\":\"user-29\",\"sex\":\"男\",\"city\":\"城市-29\",\"sign\":\"签名-29\",\"experience\":647,\"logins\":107,\"wealth\":97450636,\"classify\":\"酱油\",\"score\":27}]}";
            //return Json(jos);

        }

        #endregion

        /// <summary>
        /// 无效
        /// </summary>
        /// <param name="depId"></param>
        /// <returns></returns>
        private string GetDepName(int ? depId)
        {
            return "测试";
            if (depId==null)
            {
                return "";
            }

            var data=  DepartmentService.LoadEntities(u=>u.ID==depId).FirstOrDefault();


            return data.DepName;

        }


        #region 删除用户数据
        public ActionResult DeleteUserInfo()
        {
            string strId = Request["strId"];
            string[] strIds = strId.Split(',');
            List<int> list = new List<int>();
            foreach (var id in strIds)
            {
                list.Add(Convert.ToInt32(id));
            }
            //将list集合存储的要删除的记录的编号传递到业务层

            if( UserInfoService.DeleteEntityes(list))
            {
                return Content("ok");
            }
            else
            {
                return Content("no");
            }

        }
        #endregion

        #region 添加用户数据

        public ActionResult AddUserInfo(UserInfo userInfo)
        {

         

            userInfo.DelFlag = (short)DeleteEnumType.Normarl;
            userInfo.ModifiedOn = DateTime.Now;
            userInfo.SubTime = DateTime.Now;
            userInfo.DepId =int.Parse( Request.Form["DepName"]);

            //根据depid查询级别 存入数据库中
            var data = DepartmentService.LoadEntities(u => u.ID == userInfo.DepId).FirstOrDefault();
            userInfo.Sort= data.Level;

            UserInfoService.AddEntity(userInfo);
            return Content("ok");
        }

        #endregion
        #region 显示添加数据页面 ShowAddInfo
        public ActionResult ShowAddInfo()
        {
            ParentDropDownList();
            return View();
        }


        #endregion

        public ActionResult ShowEditInfoView()
        {
            int id = int.Parse(Request["id"]);
            UserInfo model = UserInfoService.LoadEntities(u => u.ID == id).FirstOrDefault();
            ParentDropDownList();
            return View(model);
        }



        #region 展示要修改的数据

        //public ActionResult ShowEditInfo()
        //{
        //    int id = int.Parse(Request["id"]);
        //    var userInfo = UserInfoService.LoadEntities(u => u.ID == id).FirstOrDefault();
        //    //允许Get请求
        //    return Json(userInfo, JsonRequestBehavior.AllowGet);


        //}

        
        #endregion

        #region 完成用户数据的更新
        public ActionResult EditUserInfo(UserInfo entity)
        {
            //1.根据主键ID查询数据
            UserInfo userinfo = UserInfoService.LoadEntities(u => u.ID == entity.ID).FirstOrDefault();
            if (entity == null)
            {
                return Content("no");
            }

            #region 2.设置要修改的数据

            userinfo.UName = entity.UName;

            userinfo.Remark = entity.Remark;
            userinfo.ModifiedOn = DateTime.Now;
            userinfo.DepId = entity.DepId;
           // userinfo.UPwd = entity.UPwd;

            //根据depid查询级别 存入数据库中
            var data = DepartmentService.LoadEntities(u => u.ID == userinfo.DepId).FirstOrDefault();
            userinfo.Sort = data.Level;
            #endregion


            //3.更新数据，并返回
            if (UserInfoService.UpdateEntity(userinfo))
            {
                return Content("ok");
            }
            else
            {
                return Content("no");
            }


            //int id = int.Parse(Request["id"]);
            //UserInfo userInfo = UserInfoService.LoadEntities(u => u.ID == id).FirstOrDefault();

            ////UserInfo userInfo = UserInfoService.LoadEntities(u => u.ID == entity.ID).FirstOrDefault();
            ////if (userInfo == null)
            ////{
            ////    return Content("no");
            ////}

            //userInfo.ModifiedOn = DateTime.Now;
            //userInfo.DepId = 2;
            //userInfo.UPwd = "1111";
            //if ( UserInfoService.UpdateEntity(userInfo))
            //{
            //    return Content("ok");
            //}
            //else
            //{
            //    return Content("no");
            //}
           // return Content("ok");

        }
        #endregion

        #region 为用户分配角色 ShowSetUserRoleInfo
        public ActionResult ShowSetUserRoleInfo()
        {
            int userId =Convert.ToInt32( Request["userId"]);

            UserInfo userInfo = UserInfoService.LoadEntities(u => u.ID == userId).FirstOrDefault();

            ViewBag.UserInfo = userInfo;
            short delFlag=(short)DeleteEnumType.Normarl;
            //查询所有角色信息
            var roleInfoList = RoleInfoService.LoadEntities(u => u.DelFlag == delFlag).ToList();
            //找出用户已经有的角色的编号
            var userRoleIdList = (from r in userInfo.RoleInfo
                                  select r.ID).ToList();
            ViewBag.AllRoleInfo = roleInfoList;
            ViewBag.AllExistRoleId = userRoleIdList;

            return View();
        }
        #endregion

        #region 完成对用户角色的分配
        

        public ActionResult SetUserRole()
        {
            int userId = int.Parse(Request["userId"]);
            //接受所有的复选框值
            //Request.Form.AllKeys
            String[] AllKeys = Request.Form.AllKeys;
            //获取角色编号
            List<int> list = new List<int>();
            // ckb_roleinfo_
            foreach(string key in AllKeys)
            {
                if (key.StartsWith("ckb_roleinfo_"))
                {
                    string id = key.Replace("ckb_roleinfo_", "");
                    list.Add(int.Parse(id));
                }
            }

           if ( UserInfoService.SetUserRoleInfo(userId, list))
           {
               return Content("ok");
           }
           else
               {
                   return Content("no");
               }

        }
        #endregion

        public ActionResult ShowUserAction()
        {

            int userId = int.Parse(Request["userId"]);
            var userInfo = UserInfoService.LoadEntities(u => u.ID == userId).FirstOrDefault();
            ViewBag.UserInfo = userInfo;

            short delFlag = (short)DeleteEnumType.Normarl;
            //获取所有的权限信息
            var allActionList=  ActionInfoService.LoadEntities(a => a.DelFlag == delFlag).ToList();

            //获取用户已经有的权限
            var allActionIdList = (from a in userInfo.R_UserInfo_ActionInfo
                                   select a).ToList();
            ViewBag.AllActionList = allActionList;
            ViewBag.AllActionIdList = allActionIdList;


            return View();

        }

        public ActionResult SetUserAction()
        {
            int actionId = int.Parse( Request["actionId"]);
            int userId = int.Parse(Request["userId"]);
            bool isPass = Request["isPass"] == "true" ? true : false;

            if (UserInfoService.SetUserActionInfo(actionId, userId, isPass))
            {


                return Content("ok");
            }
            else
                return Content("no");
        }

        public ActionResult ClearUserAction()
        {
            int actionId = int.Parse(Request["actionId"]);
            int userId = int.Parse(Request["userId"]);
            var r_userInfo_actionInfo= R_UserInfo_ActionInfoService.LoadEntities(
                r => r.ActionInfoID == actionId && r.UserInfoID == userId).FirstOrDefault();
           
            if (r_userInfo_actionInfo==null)
            {
                return Content("no:数据不存在!");

            }
            if (R_UserInfo_ActionInfoService.DeleteEntity(r_userInfo_actionInfo))
            {
                return Content("ok:删除成功!");
            }

            return Content("no:删除失败!");
        }

        public void ParentDropDownList()
        {
            //1.1查询YzSeriesEntity的数据  
            List<Model.Department> seriesList = DepartmentService.LoadEntities(u => u.ParentId == 0).ToList();
            List<SelectListItem> selectList = new List<SelectListItem>();
      
                    foreach (var plitem in seriesList)
                    {
                        string parentName = plitem.DepName;
                        string parentId = plitem.ID.ToString();
                        selectList.Add(new SelectListItem
                        {
                            Text = "├-" + parentName,
                            Value = parentId
                        });

                        int pid = plitem.ID;
                        string tag = "　|- ";
                        ChildrenList(pid, tag, selectList);
                    }
                    ViewBag.DevNameList = new SelectList(selectList, "Value", "Text");
                 
            
           
        }
        public void ChildrenList(int pid, string tag, List<SelectListItem> selectList)
        {
            StringBuilder strWhere = new StringBuilder();
           // var childrenList = bll.GetModelList(strWhere.ToString()).Where(d => d.ParentId == pid);
            var childrenList =  DepartmentService.LoadEntities(u => u.ParentId==pid).ToList();

            foreach (var clitem in childrenList)
            {
                string clname = tag + clitem.DepName;
                string clid = clitem.ID.ToString();
                selectList.Add(new SelectListItem
                {
                    Text = clname,
                    Value = clid
                });
                int pid2 = clitem.ID;
                string tag2 = tag + " -- ";
               ChildrenList(pid2, tag2, selectList);
            }
        }
    }
}
